package org.example.ims.Controller;

import org.example.ims.DTO.Response;
import org.example.ims.DTO.UserBackDTO;
import org.example.ims.Entity.User.CustomUser;
import org.example.ims.Service.User.CustomUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping
public class UserController {
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private CustomUserDetailsService customUserDetailsService;


    @PostMapping("/login1")
    // 登录逻辑由 Spring Security 自动处理，此处可以省略或仅用于测试目的
    public String login() {
        return "请通过 /api/login POST 请求进行登录";
    }

    @GetMapping("/user")
    public Object getCurrentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication.isAuthenticated()) {
            return Map.of("user", authentication.getName());
        } else {
            return Map.of("message", "未登录");
        }
    }

    @PostMapping("/logout2")
    // 登出逻辑由 Spring Security 自动处理，此处可以省略或仅用于测试目的
    public String logout() {
        return "请通过 /api/logout POST 请求进行登出";
    }

    @PostMapping("/register/{salesmanId}")
    public ResponseEntity<Void> processRegistration(@RequestBody CustomUser user,
                                                    @PathVariable Integer salesmanId) {

        customUserDetailsService.registerUser(user,salesmanId);
        return ResponseEntity.ok().build();
    }
    @GetMapping("/user-info")
    public Response<UserBackDTO> getUserInfo() {

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Object principal = authentication.getPrincipal();

        if (principal instanceof CustomUser) {

            return  Response.success(new UserBackDTO((CustomUser) principal),"User info retrieved successfully");
        }

        // 如果 principal 不是 CustomUser（例如匿名用户），处理相应逻辑
        throw new IllegalStateException("当前用户不是 CustomUser 类型");


    }
}